﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using WLYT.Application.Interfaces;
using WLYT.Domain.Entries;
using WLYT.Domain.Model;

namespace WLYT.WMS.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class RoleController(IBaseService<Sys_Role> sysRoleService) : ControllerBase
    {
        [HttpGet]
        public async Task<Table<Sys_Role>> GetData(string search = "", int pageSize = 20, int pageIndex = 1)
        {
            Expressionable<Sys_Role> exp = Expressionable.Create<Sys_Role>();
            exp.AndIF(search != "", p => p.Name.Contains(search));
            var result = await sysRoleService.GetPageListAsync(exp, pageSize, pageIndex);
            return new Table<Sys_Role>(result.Item1, result.Item2);
        }

        [HttpGet]
        public async Task<Sys_Role> GetModel(int id)
        {
            return await sysRoleService.GetByIdAsync(id);
        }

        [HttpGet]
        public async Task<List<Sys_Role>> GetAll()
        {
            return await sysRoleService.GetListAsync();
        }

        [HttpPost]
        public async Task<bool> Save(Sys_Role model)
        {
            var query = await sysRoleService.GetByIdAsync(model.Id);
            if (query == null)
            {
                model.CreateTime = DateTime.Now;
                return await sysRoleService.InsertAsync(model);
            }
            else
            {
                query.Name = model.Name;
                query.Permission = model.Permission;
                query.UpdateTime = DateTime.Now;
                return await sysRoleService.UpdateAsync(query);
            }
        }

        [HttpPost]
        public async Task<bool> Remove(int id)
        {
            return await sysRoleService.DeleteAsync(id);
        }
    }
}
